using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace LockImage.Encryption
{
    public class RijndaelEncryptionEngine : IEncryptionEngine
    {
        #region IEncryption Members

        byte[] IEncryptionEngine.Encrypt(byte[] arrayToEncrypt, String password)
        {

            MemoryStream inStream = new MemoryStream(arrayToEncrypt);
            MemoryStream outStream = new MemoryStream();


            Rijndael RijndaelAlg = Rijndael.Create();
            byte[] key = this.generateKey(password);
            CryptoStream cStream = new CryptoStream(outStream,
                                               RijndaelAlg.CreateEncryptor(key, key),
                                                              CryptoStreamMode.Write);

            int data;
            while ((data = inStream.ReadByte()) != -1)
            {
                cStream.WriteByte((byte)data);
            }

            inStream.Close();
            cStream.Close();
            byte[] encryptedArr = outStream.ToArray();
            outStream.Close();
            inStream = null;
            outStream = null;
            cStream = null;

            return encryptedArr;
        }

        byte[] IEncryptionEngine.Decrypt(byte[] arrayToDecrypt, String password)
        {
            MemoryStream inStream = new MemoryStream(arrayToDecrypt);
            MemoryStream outStream = new MemoryStream();
            
            RijndaelManaged RMCrypto = new RijndaelManaged();
            byte[] key = this.generateKey(password);
            CryptoStream cStream = new CryptoStream(outStream, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Write);
            int data;
            while ((data = inStream.ReadByte()) != -1)
            {
                cStream.WriteByte((byte)data);
            }

            inStream.Close();
            cStream.Close();
            byte[] dencryptedArr = outStream.ToArray();
            outStream.Close();
            inStream = null;
            outStream = null;
            cStream = null;

            return dencryptedArr;

        }

        private byte[] generateKey(String password)
        {
            if (password.Length > 8)
                password = password.Substring(0, 8);
            else if (password.Length < 8)
            {
                int add = 8 - password.Length;
                for (int i = 0; i < add; i++)
                    password = password + i;
            }

            UnicodeEncoding UE = new UnicodeEncoding();
            return UE.GetBytes(password);

        }

        #endregion
    }
}
